package com.hq.zb.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private static RedisUtil redisUtil;

    @PostConstruct
    public void init() {
        redisUtil = this;
        redisUtil.redisTemplate = this.redisTemplate;
    }

    /**
     * 存对象缓存
     * @param key
     * @param value
     * @param <T>
     */
    public static <T> void setBean(String key,T value){
        if (value != null) {
            String str = JSONUtil.toJsonStr(value);
            redisUtil.redisTemplate.opsForValue().set(key, str);
        }
    }

    /**
     * 获取对象缓存
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String key, Class<T> clazz) {
        String value = redisUtil.redisTemplate.opsForValue().get(key);
        return JSONUtil.toBean(JSONUtil.parseObj(value), clazz);
    }

    /**
     * 存list对象缓存
     * @param key
     * @param list
     * @param <T>
     */
    public static <T> void setListBean(String key, List<T> list){
        if (CollectionUtil.isNotEmpty(list)) {
            String str = JSON.toJSONString(list);;
            redisUtil.redisTemplate.opsForValue().set(key, str);
        }

    }

    /**
     * 获取list对象缓存
     * @param key
     * @return
     */
    public static <T> List<T>  getListBean(String key, Class<T> clazz) {
        String value = redisUtil.redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(value)) {
            return JSONObject.parseArray(value, clazz);
        }
        return null;
    }
}
